import { queryTagPosts } from '@/services/api';
import { useQuery } from '@tanstack/react-query';
import type { IPagination, IPost, IQueryParams, ITag } from '@/interfaces';
import { useState } from 'react';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import Pagination from '@/app/[locale]/admin/common/pagination';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function QueryTagPosts({
  source,
  translatedFields,
}: {
  source: ITag;
  translatedFields: PrefixedTTranslatedFields<'tagAdminPage'>;
}) {
  const [params, setParams] = useState<IQueryParams>({
    page: 0,
  });

  const queryTagPostsQuery = useQuery(
    ['/forum', '/tags', source.id, '/posts', params],
    async (context) => {
      return (await queryTagPosts({
        id: context.queryKey[2] + '',
        query: context.queryKey[4] as any,
      })) as IPagination<IPost>;
    },
    {
      keepPreviousData: true,
    },
  );

  function onClickPrevious() {
    const data = queryTagPostsQuery.data;
    if (!data) {
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = queryTagPostsQuery.data;
    if (!data) {
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  return (
    <div className="card">
      <div className="card-header bg-transparent text-secondary">
        <i className="bi bi-view-list me-2"></i>
        {translatedFields.post}
      </div>
      <div className="card-body vstack gap-4">
        {queryTagPostsQuery.data &&
          queryTagPostsQuery.data.content.length > 0 && (
            <div className="table-responsive">
              <table className="table table-hover align-middle">
                <thead>
                  <tr className="text-nowrap">
                    <th scope="col" className="fw-normal">
                      ID
                    </th>
                    <th scope="col" className="fw-normal">
                      {translatedFields.name}
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {queryTagPostsQuery.data.content.map((item) => {
                    return (
                      <tr key={item.id} className="text-nowrap">
                        <td>{item.id}</td>
                        <td>{item.name}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}

        {queryTagPostsQuery.data &&
          queryTagPostsQuery.data.content.length === 0 && <Nodata />}

        {queryTagPostsQuery.data && (
          <Pagination
            isShow={queryTagPostsQuery.data.pageable.pages > 0}
            onPrevious={onClickPrevious}
            onNext={onClickNext}
            isPrevious={queryTagPostsQuery.data.pageable.previous}
            isNext={queryTagPostsQuery.data.pageable.next}
            translatedFields={translatedFields.pagination}
          />
        )}

        {queryTagPostsQuery.isError && (
          <Alert message={queryTagPostsQuery.error} type="error" />
        )}

        {queryTagPostsQuery.isLoading && <AlertLoad />}
      </div>
    </div>
  );
}
